#!/usr/bin/env python

import time
import model

from twisted.protocols.basic import LineReceiver

class Protocol(LineReceiver):
    '''Protocol class
    
    @author Julot <andy.julot@gmail.com>
    @since Wednesday, July 3, 2013. 17:38 PM'''
    
    lastUpdate = None
    console = None
    proxyInfo = None
    
    def lineReceived(self, data):
        self.lastUpdate = time.time()
        data = data.strip()
        if not data: return
        
        timeFormat = '%04d-%02d-%02d %02d:%02d:%02d: '
        receiving = timeFormat + 'Receiving data for device %s.\n'
        saving = timeFormat + 'Save data for device %s.\n'
        
        measurements = model.Measurement.parse(data)
        for measurement in measurements:
            l = time.localtime(self.lastUpdate)
            d = (l.tm_year, l.tm_mon, l.tm_mday, l.tm_hour, l.tm_min, l.tm_sec,
                 measurement.device)
            self.console.info(receiving % d)
            
            l = time.localtime(self.lastUpdate)
            d = (l.tm_year, l.tm_mon, l.tm_mday, l.tm_hour, l.tm_min, l.tm_sec,
                 measurement.device)
            self.console.info(saving % d)
            measurement.bulk(self.console._args.host, self.proxyInfo)
            